package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailTopInfoService;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.crm.help.StageAverageStayTimeHelp;
import com.xbongbong.crm.service.permission.CluePermissionServiceImpl;
import com.xbongbong.crm.util.CrmPermissionUtil;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.call.CallCenterService;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.CustomerUserPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetaPhonePojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.BusinessButtonService;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.appdetail.pojo.MobileDetailManagerBlockPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.TeamEditBusinessEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.form.pojo.dto.FormConfigGetDTO;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.NameUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;


/**
 * @author 吴峰
 * @date 2022/06/21 14:27
 */
@Service("clueDetailTopInfoServiceImpl")
public class ClueDetailTopInfoServiceImpl extends AbstractCrmDetailTopInfoService {


    @Resource
    private CluePermissionServiceImpl cluePermissionService;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private CallCenterService callCenterService;
    @Resource
    private StageAverageStayTimeHelp stageAverageStayTimeHelp;
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PushModel pushModel;
    @Resource
    private BusinessButtonService businessButtonService;
    @Resource
    private LinkListService linkListService;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private ClueModel clueModel;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private TagLinkModel tagLinkModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CLUE.getCode());
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        if (loginUser.isMaxDataPermission()){
            return;
        }
        //校验用户是否有查看权限
        verifyQueryPermission(formEntity.getBusinessType(), loginUser, formEntity.getSaasMark(), formEntity.getMenuId(), paasFormDataEntityExt.getFlowStatus());

        CrmPermissionUtil.checkData(paasFormDataEntityExt, subBusinessType);

        cluePermissionService.checkPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType);

    }

    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        String corpid = handlerExplainDTO.getCorpid();
        Integer businessType = handlerExplainDTO.getBusinessType();
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        list.forEach(item->explainMap.put(item.getAttr(), item));

        ParseSingleRowDataVO parseSingleRowDataVO = commonAnalysisData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);
        JSONObject data = parseSingleRowDataVO.getResult();
        handleDetailSpecialField(paasFormDataEntityExt, data,explainMap, handlerExplainDTO);

        //处理千分位
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setData(data);
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, list, false);
        return data;
    }

    @Override
    public DetailTitlePojo handleDetailFocus(FormDataDetailDTO formDataDetailDTO, Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, String userId) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        DetailTitlePojo detailTitlePojo = new DetailTitlePojo();
        detailTitlePojo.setSealPoJoList(new ArrayList<>());
        String pid = getPid(formDataDetailDTO, corpid, paasFormDataEntityExt);
        detailTitlePojo.setPid(pid);

        return detailTitlePojo;
    }

    @Override
    public MobileDetailSpecialInfoPojo getMobileDetailSpecialInfo(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formDataDetailDTO.getBusinessType();
        MobileDetailSpecialInfoPojo mobileDetailSpecialInfoPojo = super.getMobileDetailSpecialInfo(formDataDetailDTO, paasFormDataEntityExt, explainMap);
        // 评分
        mobileDetailSpecialInfoPojo.setScore(scoreRangeModel.getScoreShowValue(businessType,paasFormDataEntityExt));
        // 栗子图标
        String pid = getPid(formDataDetailDTO, corpid, paasFormDataEntityExt);
        Map<String, Object> operation = mobileDetailSpecialInfoPojo.getOperation();
        operation.put("pid", pid);
        mobileDetailSpecialInfoPojo.setOperation(operation);
        return mobileDetailSpecialInfoPojo;
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType, Integer subBusinessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType, PaasFormEntityExt formEntity, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        JSONObject dataList = entityExt.getData();
        Integer publicFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), 0);
        JSONArray bottomBlockInfo = new JSONArray();
        if (!Objects.equals(publicFlag, 1)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", 0);
            param.put("dataId", dataId);
            List<ClueUserEntity> clueUserEntityList = clueUserModel.findEntitys(param);
            Set<String> userIdIn = new HashSet<>();
            clueUserEntityList.forEach(item -> userIdIn.add(item.getUserId()));
            List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
            Map<String, UserEntity> userMap = new HashMap<>(userEntityList.size());
            userEntityList.forEach(item -> userMap.put(item.getUserId(), item));
            List<CustomerUserPojo> userPojoList = new ArrayList<>();
            clueUserEntityList.forEach(item -> {
                UserEntity userEntity = userMap.get(item.getUserId());
                if (userEntity != null) {
                    CustomerUserPojo customerUserPojo = new CustomerUserPojo(userEntity.getUserId(), userEntity.getName(), userEntity.getAvatar(), item.getIsMain());
                    userPojoList.add(customerUserPojo);
                }
            });
            bottomBlockInfo.add(new MobileDetailManagerBlockPojo(userPojoList));
        }
        return bottomBlockInfo;
    }

    @Override
    public List<MobileDetailScriptPojo> getDetailShowScript(Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public MobileDetailStatusPojo getDetailShowStatus(Integer businessType, JSONObject data) throws XbbException {
        MobileDetailStatusPojo mobileDetailStatusPojo = new MobileDetailStatusPojo();
        Integer archivedFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
        mobileDetailStatusPojo.setName("archived");
        mobileDetailStatusPojo.setValue(archivedFlag);
        return mobileDetailStatusPojo;
    }

    @Override
    public Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        Map<String, Object> param = new HashMap<>(BasicConstant.ONE);
        Set<Long> pushNotifyList = new HashSet<>();
        pushModel.getPushNotify(Collections.singletonList(dataId), corpid, XbbRefTypeEnum.CLUE.getCode(), pushNotifyList);
        if (!pushNotifyList.isEmpty()) {
            param.put("message", true);
        }
        return param;
    }

    @Override
    public JSONObject returnSaasObject(String corpid, Integer businessType, UserVO userVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        JSONObject saasReturnObj = new JSONObject();
        //快捷新建跟进记录tab栏显示与否
        saasReturnObj.put(StringConstant.QUICKFLLOWTAB, true);
        return saasReturnObj;
    }

    @Override
    public List<TopPermissionsPoJo> dingtalkHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        String corpid = formEntity.getCorpid();
        UserVO loginUser = handelDetailPojo.getLoginUser();
        JSONObject dataList = formData.getData();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, loginUser.getPermSet());

        List<TopPermissionsPoJo> topPermissions = businessButtonService.dingtalkDetailCommon(loginUser, formEntity, explainMap, formData);
        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);
        Integer archived = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
        Integer publicFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
        String clusStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
        if (Objects.equals(formData.getDel(), DelEnum.DELETE.getDel())) {
            topPermissions.removeIf(pojo-> Objects.equals(pojo.getAttr(), OperateTypeEnum.DELETE.getAlias())
                    || Objects.equals(pojo.getAttr(), OperateTypeEnum.EDIT.getAlias()));
        }
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.equals(publicFlag, BasicConstant.ONE) || Objects.equals(formData.getDel(), DelEnum.DELETE.getDel())) {
                continue;
            }
            //如果团队内没有可退回的人员，则不展示回退公海池按钮
            if(Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_BACK_SEA) || Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_BACK_SEA)){
                boolean canBackPublic = checkCanBackPublic(dataList, loginUser);
                if(!canBackPublic){
                    continue;
                }
            }
//            if (!hasUpdate && (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_ARCHIVED) || Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_CANCEL_ARCHIVED))) {
//                continue;
//            }
            if (Objects.equals(archived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_ARCHIVED)) {
                continue;
            } else if (Objects.equals(archived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_CANCEL_ARCHIVED)) {
                continue;
            }
            if (Objects.equals(clusStatus, ClueStatusEnum.INVALID.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_INVALID)) {
                continue;
            }
            if (Objects.equals(clusStatus, ClueStatusEnum.PENDING.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.FOLLOWING_UP.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_FOLLOW)) {
                    continue;
                }
            }
            if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM) && (Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.INVALID.getCode()))) {
                continue;
            }
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
            if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM)) {
                if (Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                    // 线索状态为已转换时，不展示转换操作按钮
                    continue;
                }
                // 不需要改名字
                topPermissions.add(topPermissionsPoJo);
                continue;
            }
            NameUtil.changeValue(paasBusinessTypeToName, topPermissionsPoJo);
            topPermissions.add(topPermissionsPoJo);
        }
        List<LinkListPojo> linkList = formEntity.getLinkListList();
        topPermissions.addAll(linkListService.getDingtalkCommonButton(linkList, formData.getDel(), loginUser, formData.getAppId(), formData.getFormId(), businessType, formEntity.getSaasMark(), corpid));
        return topPermissions;
    }

    @Override
    public List<ButtonPojo> handleDetailButton(FormDataDetailDTO formDataDetailDTO, HandelDetailPojo handelDetailPojo, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONObject dataList = formData.getData();
        Integer businessType = formDataDetailDTO.getBusinessType();
        UserVO userVO = formDataDetailDTO.getLoginUser();
        List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        Integer publicFlag = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
        Integer archivedFlag = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
        String clueStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(userVO, formData);
        boolean perTag = commonPermissionHelp.checkEditPermissionWithoutShareEdit(formDataDetailDTO, verifyViewPermissionDTO, explainMap);
        List<ButtonPojo> buttonPojoList = new ArrayList<>();
        for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
            if (Objects.equals(formData.getDel(), DelEnum.DELETE.getDel())) {
                // 线索回收站支持复制，其它的操作不支持
                continue;
            }
            if (Objects.equals(publicFlag, BasicConstant.ONE) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_CANCEL_ARCHIVED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_ARCHIVED)
                    || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_INVALID) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_FOLLOW))) {
                continue;
            }
            if (Objects.equals(archivedFlag, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_CANCEL_ARCHIVED)) {
                continue;
            } else if (Objects.equals(archivedFlag, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_ARCHIVED)) {
                continue;
            }
            if (Objects.equals(clueStatus, ClueStatusEnum.INVALID.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_INVALID)) {
                continue;
            }
            if (Objects.equals(clueStatus, ClueStatusEnum.PENDING.getCode()) || Objects.equals(clueStatus, ClueStatusEnum.FOLLOWING_UP.getCode()) || Objects.equals(clueStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_FOLLOW)) {
                    continue;
                }
            }
            ButtonPojo buttonPojo = new ButtonPojo();
            SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
            if (!perTag && Objects.equals(SaasButtonEnum.EDIT.getAttr(), saasButtonEnum.getAttr())) {
                continue;
            }
            BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
            buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
            buttonPojoList.add(buttonPojo);
        }
        return buttonPojoList;
    }

    @Override
    public List<WorkFlowPojo> webHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData) throws XbbException {
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Set<String> permSet = userVO.getPermSet();
        Integer businessType = handelDetailPojo.getBusinessType();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(businessType, permSet);
        // 获取对应businessType的alias
        List<String> aliasIn = WorkFlowEnum.getAliasIn(workFlowEnumList);

        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);
        JSONObject dataList = formData.getData();
        Integer publicFlag = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
        String clueStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.equals(publicFlag, BasicConstant.ONE) || Objects.equals(formData.getDel(), DelEnum.DELETE.getDel())) {
                continue;
            }
            //如果团队内没有可退回的人员，则不展示回退公海池按钮
            if(Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_BACK_SEA) || Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_BACK_SEA)){
                boolean canBackPublic = checkCanBackPublic(dataList, userVO);
                if(!canBackPublic){
                    continue;
                }
            }
            WorkFlowPojo workFlowPojo = new WorkFlowPojo();
            BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
            if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM)) {
                if (Objects.equals(clueStatus, ClueStatusEnum.TRANSFORMED.getCode()) || Objects.equals(clueStatus, ClueStatusEnum.INVALID.getCode())) {
                    continue;
                }
                // 不需要改名字
                workFlowPojoList.add(workFlowPojo);
                continue;
            }
            NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
            workFlowPojoList.add(workFlowPojo);
        }
        // 关联新建
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        workFlowPojoList.addAll(linkListService.getCommonButton(linkList, formData.getDel(), handelDetailPojo.getLoginUser(), formData.getAppId(), formData.getFormId(), handelDetailPojo.getBusinessType(), SaasMarkEnum.SAAS.getCode(), corpid));
        return workFlowPojoList;
    }

    @Override
    public DataDetailPojo handleDetailData(Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, String userId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
        String corpid = handlerExplainDTO.getCorpid();
        Long formId = paasFormDataEntityExt.getFormId();

        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(handlerExplainDTO.getExplainList());
        // 呼叫中心权限
        boolean isActiveCall = callCenterService.isOpenCallAndAgent( corpid, userId);
        List<DetaPhonePojo> dial = new ArrayList<>();
        if ( isActiveCall ) {
            dial = callCenterService.cusCallPhone(paasFormDataEntityExt.getData(), businessType, corpid, explainMap, handlerExplainDTO);
        }
        // 呼叫中心号码
        dataDetailPojo.setDial(dial);
        //阿里云呼叫中心权限
        boolean isActiveAliyunCall = callCenterService.isActiveAliyunCall(corpid, userId).IsActiveAliyunAndHasRole();
        if ( isActiveAliyunCall ) {
            List<DetaPhonePojo> aliyunCallCenterDial = callCenterService.cusCallPhone(paasFormDataEntityExt.getData(), businessType, corpid, explainMap, handlerExplainDTO);
            if(CollectionUtils.isNotEmpty(aliyunCallCenterDial) && StringUtil.isNotEmpty(aliyunCallCenterDial.get(0).getPhoneNum())){
                dataDetailPojo.setAliyunCallCenterDial(aliyunCallCenterDial);
            }
        }
        // 外链
        Integer outerLinkShare = setOuterLinkShare(corpid, formId);
        dataDetailPojo.setHasOuterLinkShare(outerLinkShare);
        return dataDetailPojo;
    }
    @Override
    public void handleDetailSpecialField(PaasFormDataEntityExt formData, JSONObject data, Map<String, FieldAttrEntity> explainMap, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        String corpid = handlerExplainDTO.getCorpid();
        Integer businessType = handlerExplainDTO.getBusinessType();
        Long formId = formData.getFormId();
        FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
        formConfigGetDTO.setCorpid(corpid);
        formConfigGetDTO.setBusinessType(businessType);
        formConfigGetDTO.setFormId(formId);
        Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
        String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig());
        Long lastTime = FastJsonHelper.getLongFromFormData(data, ClueEnum.LAST_CONNECT_TIME.getAttr());
        if(lastConnectTime != null){
            String time = Objects.equals(lastConnectTime, "1") ? DateTimeUtil.getLastConnectTimeStr(lastTime) : DateUtil.getString(lastTime * 1000L, DateUtil.SDFYMDHM);
            data.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), time);
        }
    }

    @Override
    public List<SummaryDataPoJo> getSummaryList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Long dataId = formDataDetailDTO.getDataId();
        List<SummaryDataPoJo> summaryList =getCommonSummaryList(formData, formEntity, list, explainMap, data);
        Map<Long,String> publicTagMap = tagLinkModel.getCluePublicTag(corpid, Arrays.asList(dataId));
        if (Objects.nonNull(publicTagMap) && publicTagMap.containsKey(dataId)){
            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
            summaryDataPoJo.setAttr(TagEnum.TAG_RETURN_PUBLIC_CLUE.getAttr());
            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.RETURN_PUBLIC));
            String memo = publicTagMap.get(dataId);
            summaryDataPoJo.setValue(Arrays.asList(memo));
            summaryList.add(summaryDataPoJo);
        }
        //线索详情 转移标签
        Map<Long,String> transferTagMap = tagLinkModel.getTransferTag(corpid, Arrays.asList(dataId),XbbRefTypeEnum.CLUE_TRANSFER.getCode());
        if (Objects.nonNull(transferTagMap) && transferTagMap.containsKey(dataId)){
            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
            summaryDataPoJo.setAttr(TagEnum.TAG_TRANSFER_PUBLIC_CLUE.getAttr());
            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.TRANSFER_PUBLIC));
            String memo = transferTagMap.get(dataId);
            summaryDataPoJo.setValue(Arrays.asList(memo));
            summaryList.add(summaryDataPoJo);
        }

        return summaryList;
    }

    /**
     * 摘要公共方法，手机端和pc端都会调，如有改动，都要覆盖测试
     * @param formData
     * @param formEntity
     * @param list
     * @param explainMap
     * @param data
     * @return
     * @throws XbbException
     */
    private List<SummaryDataPoJo> getCommonSummaryList(PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<SummaryDataPoJo> summaryList = ExplainUtil.getSpecialSummaryList(formEntity.getSummaryList(), data, explainMap, formData);
        //公海池特殊处理 负责人->前负责人
        changeOwnerIdAttrName(data, summaryList);

        return summaryList;
    }

    @Override
    public List<SummaryDataPoJo> getLabelList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> explainList, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        // 解析标签
        List<SummaryDataPoJo> labelsList = ExplainUtil.getSpecialSummaryList(formEntity.getLabelsList(), data, explainMap, formData);
        //客户公海池特殊处理 负责人->前负责人
        changeOwnerIdAttrName(data, labelsList);
        return labelsList;
    }
    /**
     * 将公海池的负责人改为前负责人
     * @param data
     * @param labelsList
     */
    private static void changeOwnerIdAttrName(JSONObject data, List<SummaryDataPoJo> labelsList) {
        //客户公海池特殊处理 负责人->前负责人
        if (Objects.equals(data.getInteger(ClueEnum.IS_PUBLIC.getAttr()), 1)) {
            for(SummaryDataPoJo poJo : labelsList) {
                if (Objects.equals(poJo.getAttr(), ClueEnum.OWNER_ID.getAttr())) {
                    poJo.setAttrName(FieldTypeEnum.PRE_OWNER_ID.getDescription());
                    break;
                }
            }
        }
    }
    @Override
    public JSONArray getSecondTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Long dataId = formData.getId();
        List<SummaryDataPoJo> summaryList = getCommonSummaryList(formData, formEntity, list, explainMap, data);
        JSONArray secondTitle = getSecondTitleList(summaryList, data, formDataDetailDTO.getCorpid(), formEntity.getId());

        String cStayTimeStr = stageAverageStayTimeHelp.getAverageStayTime(formDataDetailDTO.getSaasMark(), formDataDetailDTO.getBusinessType(), corpid, formEntity.getId(), dataId, formData.getData());

        if (cStayTimeStr != null) {
            JSONObject cusObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_STAGE_LONG), cStayTimeStr);
            secondTitle.add(cusObj3);
        }
        return secondTitle;
    }

    @Override
    public JSONArray getTagList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formEntity.getBusinessType();
        Long dataId = formData.getId();
        String userId = formDataDetailDTO.getUserId();
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        JSONArray tags = getTags(labelsList, corpid, businessType, dataId, userId);
        return tags;
    }

    @Override
    public String getTitle(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return TitleUtil.getWebTitle(formTitleList);
    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer publicFlag = FastJsonHelper.getIntegerOrDefaultFromFormData(formData.getData(), ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
        //判断线索阶段是否开启
        Integer businessType = handelDetailPojo.getBusinessType();
        boolean ifClueStageOpen = CommonHelp.ifStageOpen(businessType, explainMap, handlerExplainDTO);
        // 判断线索电话字段是否可见
        boolean clueMobile = commonHelp.attrCanSee(ClueEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
        if(clueMobile){
            List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(ClueEnum.PHONE.getAttr()).getSubForm().getItems();
            Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
            explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
            boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
            if(!text2CanSee){
                clueMobile = false;
            }
        }
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        String userId= userVO.getUserId();
        // 判断当前公司有没有开启呼叫中心
        boolean isActiveCall = callCenterService.isOpenCallAndAgent(corpid, userId);
        List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getTabByBusinessTypeAndPermission(businessType, userVO.getPermSet(), handlerExplainDTO.getPlatform());
        boolean isActiveAliyunCall = callCenterService.isActiveAliyunCall(corpid, userId).IsActiveAliyunAndHasRole();
        // 获取对应businessType的alias
        List<String> aliasIn = BusinessDetailTabEnum.getAliasIn(tabEnumList);

        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        // 兼容原呼叫中心  开通了其中一个就显示 通话记录tab
        isActiveCall = isActiveCall||isActiveAliyunCall;
        // 判断应用是否启用
        boolean isSmsUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.GROUP_MESSAGE.getAlias(), 1, corpid);
        // 判断当前员工有没有短信权限
        boolean canSms = isSmsUse && userVO.getPermSet().contains(ProPermissionAliasEnum.SMS_VIEW.getAlias()) ;


        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            if (Objects.equals(publicFlag, 1) && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SALE_TEAM)) {
                continue;
            }
            // 移动端不需要阶段历史
            if (Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_STAGE) && Objects.equals(handlerExplainDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                continue;
            }
            if (Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_STAGE) && !ifClueStageOpen) {
                continue;
            }
            if (!isActiveCall && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_CALL_LOG)) {
                continue;
            }
            if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SMS_SEND_AND_REPLY)) {
                continue;
            }
            // 短信往来tab
            if (!clueMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SMS_SEND_AND_REPLY)) {
                continue;
            }
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, formData.getDel(), linkList));

        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }


    @Override
    public void returnVO(PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, MobileFormCommonDetailVO mobileFormCommonDetailVO, String userId) throws XbbException {
        mobileFormCommonDetailVO.setHasOuterLinkShare(setOuterLinkShare(formEntity.getCorpid(), formEntity.getId()));
        mobileFormCommonDetailVO.setDistributorMark(formEntity.getDistributorMark());
        mobileFormCommonDetailVO.setPaasFormEntity(formEntity);
        //判断工商查询能否使用
        if ( fineClueHelp.isFineClueByCorpid(formData.getCorpid(), XbbRefTypeEnum.CLUE.getCode(), formEntity.getDistributorMark())) {
            mobileFormCommonDetailVO.setIsFineClue(1);
        }
    }

    @Override
    protected void setFormEntity(FormDataDetailDTO formDataDetailDTO, PaasFormEntityExt form, FormDataDetailVO formDataDetailVO) {
        formDataDetailVO.setPaasFormEntityExt(form);
        //判断工商查询能否使用
        if ( fineClueHelp.isFineClueByCorpid(formDataDetailDTO.getCorpid(), XbbRefTypeEnum.CLUE.getCode(), formDataDetailDTO.getDistributorMark())) {
            formDataDetailVO.setIsFineClue(1);
        }
    }

}
